import threading
import socket


def func(new_socket, new_address):
    print(f"{str(new_address)}已上线")
    recv_data = new_socket.recv(4096)
    if not recv_data:
        print(f"{str(new_address)}已下线")
        new_socket.close()
        return

    path_info = recv_data.decode().split(' ')[1]
    if path_info == "/":
        path_info = '/index.html'

    try:
        with open("static" + path_info, "rb") as file:
            file_data = file.read()
    except:
        with open("static/404.html", 'rb') as file:
            file_data = file.read()
        http_data = 'HTTP/1.1 404 Not Found\r\nServer: PWS\r\n\r\n'.encode() + file_data
    else:
        http_data = 'HTTP/1.1 200 OK\r\nServer: PWS\r\n\r\n'.encode() + file_data
    finally:
        new_socket.send(http_data)
        new_socket.close()




def main():
    server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    server_socket.bind(('',8080))
    server_socket.listen(128)
    while True:
        new_socket, new_address = server_socket.accept()
        threading.Thread(target=func, args=(new_socket,new_address),daemon=True).start()



if __name__ == '__main__':
    main()